#!usr/bin/env python
# -*- coding:utf-8 -*-
from gevent import monkey
monkey.patch_all()
import gevent
from socket import *
print('start running...')
def talk(conn, addr):
    try:
        while True:
            data = conn.recv(1024)
            print('%s:%s %s' % (addr[0], addr[1], data.decode('utf-8')))
            conn.send((data.upper() + '服务端收到并返回'.encode('utf-8')))
    finally:
        conn.close()


def server(ip, port):
    server = socket(AF_INET, SOCK_STREAM)
    try:
        server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        server.bind((ip, port))
        server.listen(5)
        while True:
            conn, addr = server.accept()  # 等待链接
            gevent.spawn(talk, conn, addr)
            # 异步执行 （p =Process(target=talk,args=(coon,addr))
            # p.start()）相当于开进程里的这两句
    finally:
        server.close()

if __name__ == '__main__':
    server('127.0.0.1', 8081)
